package com.kbbywyclient.ui.adapter.base;

import android.support.annotation.IdRes;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.kbbywyclient.R;

import java.util.List;


/**
 * Created by FHW
 * on 2017/2/6
 */
public abstract class BaseAdapter<T> extends RecyclerView.Adapter {
    public static final int TYPE_NO_DATA=-1;
    public static final int TYPE_NORMAL=0;
    protected int mLayoutId;
    protected List<T> mData;
    protected Holder mHolder;

    public BaseAdapter(List<T> data,int layoutId){
        this.mData=data;
        this.mLayoutId=layoutId;
    }

    public void setDataSource(List<T> data){
        if(data!=null){
            this.mData=data;
            notifyDataSetChanged();
        }
    }

    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater=LayoutInflater.from(parent.getContext());
        if(viewType==TYPE_NORMAL){
            View itemView= inflater.inflate(mLayoutId,parent,false);
            mHolder =new Holder(itemView);
            return mHolder;
        }
        if(viewType==TYPE_NO_DATA){
            View noDataView=inflater.inflate(R.layout.item_recycler_no_data,parent,false);
            return new RecyclerView.ViewHolder(noDataView) {
            };
        }
        return null;
    }

    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position){
        if(holder instanceof Holder){
            convert((Holder) holder,mData.get(position),position);
        }
    }

    public abstract void convert(Holder holder,T t,int position);

    @Override
    public int getItemCount() {
        return (mData == null||mData.size()==0) ? 1 : mData.size();
    }

    protected Object getData(int position) {
        return mData == null ? null : mData.get(position);
    }

    @Override
    public int getItemViewType(int position) {
        return (mData==null||mData.size()==0)?TYPE_NO_DATA:TYPE_NORMAL;
    }

    public static class Holder extends RecyclerView.ViewHolder{
        public SparseArray<View> mViews;

        public Holder(View itemView) {
            super(itemView);
            mViews=new SparseArray<>();
        }

        public <T extends View> T getView(@IdRes int viewId){
            View view=mViews.get(viewId);
            if(view==null){
                view=itemView.findViewById(viewId);
                if(view!=null){
                    mViews.put(viewId,view);
                }
            }
            return (T)view;
        }

        public void setText(int textViewId,CharSequence content){
            TextView textView=getView(textViewId);
            if(textView!=null){
                textView.setText(TextUtils.isEmpty(content)?"":content);
            }
        }
    }

}
